package main

import (
	"encoding/json"
	"fmt"
)

type Student struct {
	Name string
	Sex  string
}

type Class struct {
	Name     string
	Students []*Student
}

func main() {
	c := &Class{
		Name:     "知青班",
		Students: make([]*Student, 0, 5),
	}

	for i := 0; i < 5; i++ {
		stu := &Student{
			Name: fmt.Sprintf("stu%02d", i),
			Sex:  "男",
		}
		c.Students = append(c.Students, stu)
	}

	fmt.Printf("json:%s\n", c)

	data, error := json.Marshal(c)
	if error != nil {
		fmt.Println("json marshal failed")
		return
	}
	fmt.Printf("json:%s\n", data)
	// json反序列化：json格式的字符串--》结构体

	str := `{"Name":"知青班","Students":[{"Name":"stu00","Sex":"男"},{"Name":"stu01","Sex":"男"},{"Name":"stu02","Sex":"男"},{"Name":"stu03","Sex":"男"},{"Name":"stu04","Sex":"男"}]}`
	c1 := &Class{}

	error = json.Unmarshal([]byte(str), c1)

	if error != nil {
		fmt.Println("json unmarshal failed!")
		return
	}
	fmt.Printf("json:%s\n", c1)

}
